class CreateOrderOptions < ActiveRecord::Migration
  def self.up
    create_table :order_options do |t|
      t.string      :name
      t.decimal     :cost, :precision => 8, :scale => 2
      t.boolean     :quantifiable
      t.timestamps
    end

    # add in defaults
    load_from_csv("order_options", order_option_data)
  end

  def self.load_from_csv(table_name, data)
    column_clause = nil
    is_header = false
    cnx = ActiveRecord::Base.connection
    ActiveRecord::Base.silence do
      reader = CSV::Reader.create(data)

      columns = reader.shift.map {|column_name| cnx.quote_column_name(column_name) }
      column_clause = columns.join(', ')

      reader.each do |row|
        next if row.first.nil? # skip blank lines
        raise "No table name defined" if !table_name
        raise "No header defined" if !column_clause
        values_clause = row.map {|v| cnx.quote(v).gsub('\\n', "\n").gsub('\\r', "\r") }.join(', ')
        sql = "INSERT INTO #{table_name} (#{column_clause}) VALUES (#{values_clause})"
        cnx.insert(sql)
      end
    end
  end

  def self.order_option_data
  <<'END_OF_DATA'
"id","name","cost","quantifiable","created_at","updated_at"
1,"Session Highlight Video","65","","",""
2,"Customized Banner","25","1","",""
3,"Business Card Invitations (set of 100)","40","1","",""
4,"Post Card Invitations (set of 24)","50","1","",""
5,"Magnetic Invitation","4","1","",""
6,"Single Fold Invitations (set of 24)","65","1","",""
7,"Hard Cover Album","15","1","",""
8,"Soft Cover Album","10","1","",""
END_OF_DATA
  end

  def self.down
    drop_table :order_options
  end
end
